/**
 * Copyright (c) 2020-2030 LiuBoTao [1211265557@qq.com]
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.amos.server.modules.upms.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaCheckSafe;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.amos.core.basic.annotation.Log;
import org.amos.core.basic.annotation.ParamCheck;
import org.amos.core.basic.base.BaseController;
import org.amos.core.basic.constant.SystemConstant;
import org.amos.core.basic.exception.ServiceException;
import org.amos.core.basic.utils.AmosUtils;
import org.amos.core.basic.vo.R;
import org.amos.satoken.domain.bo.AuthInfo;
import org.amos.satoken.utils.PwdUtils;
import org.amos.satoken.utils.UserUtils;
import org.amos.server.modules.upms.dto.UserDTO;
import org.amos.server.modules.upms.dto.UserPwdDTO;
import org.amos.server.modules.upms.dto.UserStatusDTO;
import org.amos.server.modules.upms.entity.User;
import org.amos.server.modules.upms.service.IMenuService;
import org.amos.server.modules.upms.service.IUserRoleService;
import org.amos.server.modules.upms.service.IUserService;
import org.amos.server.modules.upms.vo.UserVO;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotEmpty;
import java.util.Objects;
import java.util.Set;

/**
 * 系统用户 前端控制器
 *
 * @author liubt
 * @since 2020-12-20
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/system/user")
public class UserController extends BaseController {

    private final IUserService userService;
    private final IMenuService menuService;
    private final IUserRoleService userRoleService;

    @GetMapping("/list")
    @ApiOperation(value = "用户数据列表")
    @SaCheckPermission("user:list")
    @Log(value = "用户数据列表", logResultInfo = false)
    public R list(UserDTO dto) {
        IPage<UserVO> page = userService.selectUserPage(initPage(dto), dto);
        return R.ok(page);
    }

    @PostMapping("/update")
    @ApiOperation(value = "更新用户数据")
    @SaCheckPermission("user:update")
    @Log(value = "更新用户数据", logResultInfo = false)
    public R update(@RequestBody @Validated UserDTO dto) {
        userService.saveOrUpdateUser(dto);
        return R.ok();
    }

    @PostMapping("/update/pwd")
    @ApiOperation(value = "修改密码")
    @ParamCheck(message = "缺少必要参数")
    @SaCheckPermission("user:update")
    @Log(value = "修改密码", logResultInfo = false)
    public R updatePwd(@RequestBody UserPwdDTO dto) {
        long userId = StpUtil.getLoginIdAsLong();
        dto.setId(userId);
        User sysUser = userService.getOne(buildWrapper(dto));
        if (!PwdUtils.match(dto.getOldPwd(), sysUser.getPassword())) {
            throw new ServiceException("当前密码输入有误!");
        }
        if (Objects.equals(dto.getOldPwd(), dto.getPwd())) {
            throw new ServiceException("新密码不能和旧密码相同!");
        }
        UpdateWrapper uw = new UpdateWrapper();
        uw.eq(AmosUtils.toDbField(User::getId), userId);
        User user = new User();
        user.setPassword(PwdUtils.encode(dto.getPwd()));
        userService.update(user, uw);
        return R.ok();
    }

    @GetMapping("/info")
    @ApiOperation(value = "获取用户数据")
    @Log(value = "获取用户数据", logResultInfo = false)
    public R getInfo() {
        AuthInfo authInfo = UserUtils.getUser();
        UserVO userVO = AmosUtils.copy(authInfo, UserVO.class);
        return R.ok(userVO);
    }

    @PostMapping("/reset/pwd")
    @ApiOperation(value = "重置用户密码")
    @ParamCheck(message = "缺少必要参数")
    @SaCheckPermission("user:update")
    @Log(value = "重置用户密码", logResultInfo = false)
    public R resetPwd(@RequestBody @NotEmpty Set<Long> ids) {
        userService.resetPwd(ids);
        return R.ok("重置成功!新密码为：" + SystemConstant.SYS_DEFAULT_PWD);
    }

    @PostMapping("/set/status")
    @ApiOperation(value = "设置用户状态")
    @SaCheckPermission("user:update")
    @Log(value = "设置用户状态", logResultInfo = false)
    public R setStatus(@RequestBody @Validated UserStatusDTO dto) {
        userService.setStatus(dto);
        return R.ok();
    }

    @PostMapping("/remove")
    @ApiOperation(value = "删除用户数据")
    @ParamCheck(message = "缺少必要参数")
    @SaCheckPermission("user:update")
    @SaCheckSafe
    @Log(value = "删除用户数据", logResultInfo = false)
    public R remove(@RequestBody Set<Long> ids) {
        userService.removeUser(ids);
        return R.ok();
    }
}
